import { t } from 'i18next';
import React, { useState } from 'react';
import { type NodeProps } from 'reactflow';
import { useContextSelector } from 'use-context-selector';

import CollapsibleSection from '@/components/CollapsibleSection';
import { FlowNodeInputTypeEnum, FlowNodeOutputTypeEnum } from '@/types/workflow/constant';
import { FlowNodeItemType } from '@/types/workflow/node';

import { WorkflowContext } from '../../../context';
import Container from '../../flow/Container';
import IOTitle from '../../flow/IOTitle';
import NodeCard from '../render/NodeCard';
import RenderInput from '../render/RenderInput';
import RenderOutput from '../render/RenderOutput';
import RenderToolInput from '../render/RenderToolInput';

const NodeTool = ({ data, selected }: NodeProps<FlowNodeItemType>) => {
  const { nodeId, inputs, outputs } = data;
  const [expandedSections, setExpandedSections] = useState<Set<'output' | 'input' | 'params'>>(
    new Set(['input']),
  );

  const toggleSection = (section: 'output' | 'input' | 'params') => {
    setExpandedSections((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(section)) {
        newSet.delete(section);
      } else {
        newSet.add(section);
      }
      return newSet;
    });
  };
  const splitToolInputs = useContextSelector(WorkflowContext, (v) => v.splitToolInputs);
  const { commonInputs, isTool } = splitToolInputs(inputs, nodeId);

  return (
    <NodeCard minW="350px" selected={selected} {...data}>
      {isTool && (
        <CollapsibleSection
          title="MCP参数"
          subtitle={t('调用MCP所需的参数')}
          isExpanded={expandedSections.has('input')}
          onToggle={() => toggleSection('input')}
          type="input"
          className="pb-2"
        >
          <div className="pb-2">
            <RenderToolInput nodeId={nodeId} inputs={inputs} />
          </div>
        </CollapsibleSection>
      )}
      {commonInputs.filter((item) => !item.renderTypeList.includes(FlowNodeInputTypeEnum.hidden))
        .length > 0 && (
        <Container>
          <IOTitle text={t('common:Input')} />
          <RenderInput nodeId={nodeId} flowInputList={commonInputs} />
        </Container>
      )}

      <CollapsibleSection
        title={t('workflow.node.output')}
        subtitle={t('workflow.node.output_desc')}
        isExpanded={expandedSections.has('output')}
        onToggle={() => toggleSection('output')}
        type="output"
        className="pb-3"
      >
        {outputs.filter((output) => output.type !== FlowNodeOutputTypeEnum.hidden).length > 0 && (
          <div className="px-2">
            <RenderOutput flowOutputList={outputs} nodeId={nodeId} />
          </div>
        )}
      </CollapsibleSection>
    </NodeCard>
  );
};

export default React.memo(NodeTool);
